package com.controller;

import com.entity.Admin;
import com.entity.Department;
import com.entity.Salary;
import com.form.EmployeeInfoForAdmin;
import com.form.Message;
import com.form.SalaryInfoForAdmin;
import com.service.AdminService;
import com.service.DepartmentService;
import com.service.EmployeeService;
import com.service.SalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 管理员控制器
 * @author z'y
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    /**
     * The Admin service.
     */
    @Autowired
    AdminService adminService;
    /**
     * The Employee service.
     */
    @Autowired
    EmployeeService employeeService;
    /**
     * The Department service.
     */
    @Autowired
    DepartmentService departmentService;
    /**
     * The Salary service.
     */
    @Autowired
    SalaryService salaryService;

    /**
     * 通过id查找管理员，测试用的
     *
     * @param id the id
     * @return the string
     */
    @GetMapping(value = "/{id}")
    public String doLogin(@PathVariable(value = "id") int id) {
        //从数据库中查找管理员信息
        Admin admin = adminService.findManagerById(id);
        return admin.toString();
    }
    /**
     * 返回管理员登录页面jsp
     *
     * @return the string
     */
    @GetMapping(value = "/login")
    public String doLogin(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");
        if(admin != null){
            return "redirect:getDepartInfo";
        }
        Message message = new Message(0,"您尚未登录！请先登录。");
        return "adminLogin";
    }
    /**
     * 登录
     * 实现管理员登录
     *
     * @return the string
     */
    @PostMapping(value = "/login")
    public String doLogin(@RequestParam(value = "username", defaultValue = "") String username,
                          @RequestParam(value = "password", defaultValue = "") String password, HttpSession session, Model model) {
        //判断是否已经登录
        Admin admin = (Admin) session.getAttribute("admin");
        if(admin != null){
            Message message = new Message(0,"您已登录，请勿重复登录。请先退出后再登录。");
            model.addAttribute("message",message);
            return "adminLogin";
        }
        //从数据库中查找管理员信息
       admin = adminService.findByUserNameAndPwd(username, password);
        if (admin != null) {
            //登陆成功，返回managerView页面
            session.setAttribute("admin", admin);
            return "redirect:getDepartInfo";//admin主页面
        } else {
            //登陆失败，返回loginErr页面
            model.addAttribute("message",new Message(0,"The password not right."));
            return "adminLogin";
        }
    }

    /**
     * 注销.
     *
     * @param request  the request
     * @param response the response
     * @return the string
     */
    @GetMapping(value = "/logout")
    public String doLogout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        // Cookie[] cookies = request.getCookies();
        request.getSession().removeAttribute("admin");
        return "adminLogin";
    }

    @GetMapping("/checkAllEmployees")
    public String checkEmployees(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                 Model model,HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        Message message=(Message) session.getAttribute("message");
        if(message!=null){
            session.removeAttribute("message");
            model.addAttribute("message",message);
        }
        Salary salary=(Salary)session.getAttribute("salary");
        if(salary!=null){
            model.addAttribute("salary",salary);
        }
        PaginationSupport<EmployeeInfoForAdmin> employees = employeeService.checkAllemployees(pageNo, pageSize);
        model.addAttribute("employeeList", employees);
        return "employeeList";
    }

    /**
     * 添加一个员工，为一个员工建立一个账号
     *
     * @param username     the username
     * @param departmentId the department id
     * @param levelId      the level id
     * @param model        the model
     * @param session      the session
     * @return the string
     */
    @PostMapping("/addEmployee")
    public String addEmployee(@RequestParam("username")String username,
                              @RequestParam("departmentId") int departmentId,
                              @RequestParam("levelId") int levelId,
                              Model model,HttpSession session){
        Message message = employeeService.addEmployee(username,departmentId,levelId);
        session.setAttribute("message",message);
        return "redirect:checkAllEmployees";
    }

    /**
     * 删除
     * 删除一个员工通过员工用户名(不是删除，只是将状态改为了离职)
     *
     * @param username the username
     * @param session  the session
     * @return the string
     */
    @PostMapping("/deleteEmployee")
    public String deleteEmployees(@RequestParam("username") String username,
                                  HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        Message message = employeeService.deleteEmployeeByUsername(username);
        session.setAttribute("message",message);
        return "redirect:checkAllEmployees";
    }
    /**
     * 更改
     * 更新一个员工信息.

     * @return the string
     */
    @PostMapping("/updateEmployeeInfo")
    public String updateEmployee(@RequestParam("username") String username,
                                 @RequestParam("departmentId") int departmentId,
                                 @RequestParam("levelId") int levelId,
                                 HttpSession session) {
        Message message = employeeService.updateEmployeeInfoForAdmin(username,departmentId,levelId);
        session.setAttribute("message",message);
        return "redirect:checkAllEmployees";
    }

    @GetMapping("/getEmployeeInfo")
    public String getEmployeeInfo(
            Model model,HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        int employee1Count = employeeService.countEmployeeByLevel(1);
        int employee2Count = employeeService.countEmployeeByLevel(2);
        int employee3Count = employeeService.countEmployeeByLevel(3);



// 将结果添加到模型中
        model.addAttribute("firstGroup", employee1Count);
        model.addAttribute("secondGroup", employee2Count);
        model.addAttribute("thirdGroup", employee3Count);

        return "eChart";
    }

    /**
     * 查找
     * 搜索员工，可以根据员工名字，部门名字，等级名字
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param keys     the keys
     * @param model    the model
     * @return the string
     */
    @GetMapping("/findEmployeeByKeys")
    public String findEmployeesByKeys(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                      @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                      @RequestParam("keys") String keys, Model model) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PaginationSupport<EmployeeInfoForAdmin> employeeList = employeeService.findEmployeesByKeys(pageNo, pageSize, keys);
        System.out.println(employeeList.getItems().toString());
        model.addAttribute("employeeList", employeeList);
        return "employeeList";
    }
    /**
     * 查看
     * 查看部门列表信息
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param model    the model
     * @param session  the session
     * @return the string
     */
    @GetMapping("/checkAllDepart")
    public String checkDeparts(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                               Model model,HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        Message message=(Message) session.getAttribute("message");
        if(message!=null){
            session.removeAttribute("message");
            model.addAttribute("message",message);//放入更新状态提示
        }
        PaginationSupport<Department> departs = departmentService.checkDepartments(pageNo, pageSize);
        model.addAttribute("departmentList", departs);
        //如果给出的页面大小<=0，则将其设置为10
        int department1Count = departmentService.countDepartmentByRanking("一级部门");
        int department2Count = departmentService.countDepartmentByRanking("二级部门");
        int department3Count = departmentService.countDepartmentByRanking("三级部门");

// 将结果添加到模型中
        model.addAttribute("firstGroup", department1Count);
        model.addAttribute("secondGroup", department2Count);
        model.addAttribute("thirdGroup", department3Count);


        return "dM";
    }

    @GetMapping("/getDepartInfo")
    public String getDepartInfo(
            Model model,HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        int department1Count = departmentService.countDepartmentByRanking("一级部门");
        int department2Count = departmentService.countDepartmentByRanking("二级部门");
        int department3Count = departmentService.countDepartmentByRanking("三级部门");



// 将结果添加到模型中
        model.addAttribute("firstGroup", department1Count);
        model.addAttribute("secondGroup", department2Count);
        model.addAttribute("thirdGroup", department3Count);

        int employee1Count = employeeService.countEmployeeByLevel(1);
        int employee2Count = employeeService.countEmployeeByLevel(2);
        int employee3Count = employeeService.countEmployeeByLevel(3);



// 将结果添加到模型中
        model.addAttribute("aGroup", employee1Count);
        model.addAttribute("bGroup", employee2Count);
        model.addAttribute("cGroup", employee3Count);

        return "adminView";
    }
    @GetMapping("/getOneInfo")
    public String getOneInfo(
            Model model,HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        int department1Count = departmentService.countDepartmentByRanking("一级部门");
        int department2Count = departmentService.countDepartmentByRanking("二级部门");
        int department3Count = departmentService.countDepartmentByRanking("三级部门");



// 将结果添加到模型中
        model.addAttribute("firstGroup", department1Count);
        model.addAttribute("secondGroup", department2Count);
        model.addAttribute("thirdGroup", department3Count);

        return "dChartOne";
    }



    /**
     * 更改
     * 更新一个部门信息.
     *
     * @param departmentId   the department id (不能改)
     * @param departmentName the department name
     * @param fdId           the fd id
     * @param ranking        the ranking
     * @param basicSalary    the basic salary
     * @param session        the session
     * @return the string
     */
    @PostMapping("/updateDepartmentInfo")
    public String updateDepartment(@RequestParam("departmentId") int departmentId,
                                   @RequestParam("departmentName") String departmentName,
                                   @RequestParam("fatherDepartmentId") int fdId,
                                   @RequestParam("ranking") String ranking,
                                   @RequestParam("basicSalary") double basicSalary,
                                   HttpSession session) {
        Department department = new Department();
        department.setDepartmentId(departmentId);
        department.setDepartmentName(departmentName);
        department.setRanking(ranking);
        department.setFatherDepartmentId(fdId);
        department.setBasicSalary(basicSalary);
        Message message = departmentService.updateDepart(department);//返回更新状态提示
        session.setAttribute("message",message);
        return "redirect:checkAllDepart";
    }

    /**
     * 增加
     * 增加一个部门
     * 1、首先会验证输入的信息中的父部门是否存在，不存在则会给出提示
     *
     * @param departmentName the department name
     * @param fdId           the fd id
     * @param ranking        the ranking
     * @param basicSalary    the basic salary
     * @param session        the session
     * @return the string
     */
    @PostMapping("/addDepartment")
    public String addDepartment(@RequestParam("departmentName") String departmentName,
                                @RequestParam("fatherDepartmentId") int fdId,
                                @RequestParam("ranking") String ranking,
                                @RequestParam("basicSalary") double basicSalary,
                                HttpSession session ){
        Department department = new Department();
        department.setDepartmentId(1);
        department.setDepartmentName(departmentName);
        department.setRanking(ranking);
        department.setFatherDepartmentId(fdId);
        department.setBasicSalary(basicSalary);
        Message message = departmentService.addDepart(department);//返回添加状态提示
        session.setAttribute("message", message);
        return "redirect:checkAllDepart";
    }

    /**
     * 删除
     * 通过部门id删除一个部门
     * 1、如果这个部门有子部门，无法删除
     * 2、如果这个部门有员工，无法删除
     *
     * @param departmentId the department id
     * @param session      the session
     * @return the string
     */
    @PostMapping("/deleteDepart")
    public String deleteDepart(@RequestParam("departmentId") int departmentId,
                               HttpSession session) {
        Message message = departmentService.deleteDepartmentById(departmentId);//返回删除状态提示
        session.setAttribute("message", message);
        return "redirect:checkAllDepart";
    }

    /**
     * 查找
     * 搜索一个部门，可以根据部门id或部门名字
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param keys     the keys
     * @param model    the model
     * @return the string
     */
    @GetMapping("/findDepartByKeys")
    public String findDepartsByKeys(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                    @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                    @RequestParam("keys") String keys, Model model) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PaginationSupport<Department> departmentList = departmentService.findDepartsByKeys(pageNo, pageSize, keys);
        System.out.println(departmentList.getItems().toString());
        model.addAttribute("departmentList", departmentList);
        return "dM";
    }

    /**
     * 查看
     * 查看所有工资记录（分页）
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param model    the model
     * @param session  the session
     * @return the string
     */
    @GetMapping("/checkAllSalary")
    public String checkSalary(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                              Model model,HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        Message message=(Message) session.getAttribute("message");
        if(message!=null){
            session.removeAttribute("message");
            model.addAttribute("message",message);
        }
        PaginationSupport<SalaryInfoForAdmin> salarys = salaryService.checkSalarys(pageNo, pageSize);
        System.out.println(salarys.getItems().toString());
        model.addAttribute("salaryList", salarys);
        return "salaryList";
    }

    /**
     * 通过关键字查找工资记录
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param keys     the keys
     * @param model    the model
     * @return the string
     */
    @GetMapping("/findSalaryByKeys")
    public String findSalaryByKeys(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                   @RequestParam("keys") String keys, Model model) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PaginationSupport<SalaryInfoForAdmin> salarys = salaryService.findSalaryByKeys(keys, pageNo, pageSize);
        System.out.println(salarys.getItems().toString());
        model.addAttribute("salaryList", salarys);
        return "salaryList";
    }

    /**
     * 查看
     * 查看所有员工信息，实现分页
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param model    the model
     * @param session  the session
     * @return the string
     */
    @GetMapping("/payForEmployees")
    public String payForEmployees(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                  @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                  Model model,HttpSession session) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        Message message=(Message) session.getAttribute("message");
        if(message!=null){
            session.removeAttribute("message");
            model.addAttribute("message",message);
        }
        SalaryInfoForAdmin salary=(SalaryInfoForAdmin) session.getAttribute("salary");
        if(salary!=null){
            model.addAttribute("salary",salary);
        }
        PaginationSupport<EmployeeInfoForAdmin> employees = employeeService.checkAllemployees(pageNo, pageSize);
        model.addAttribute("employeeList", employees);
        return "paySalary";
    }
    /**
     * 发放工资
     * 为某一个员工发放工资
     *
     * @param performance the performance
     * @param username    the username
     * @param session     the session
     * @return the string
     */
    @PostMapping("/paySalary")
    public String paySalaryForOne(@RequestParam("performance") String performance,
                                  @RequestParam("username") String username,
                                  HttpSession session) {
        //查看本月是否有发放工资
        Message message = salaryService.checkCurrentMonthPay(username);
        if (message.getStatus() == 1) {//本月未发放工资,发放工资成功
            //查看工资条，并发放工资
            SalaryInfoForAdmin salary = salaryService.addSalary(username, performance);
            message.setMessage("The salary pay successfully!");
            session.setAttribute("salary", salary);
            session.setAttribute("message", message);
        } else {//本月发了工资
            session.setAttribute("message", message);
        }
        return "redirect:payForEmployees";
    }
    /**
     * 查找
     * 搜索员工，可以根据员工名字，部门名字，等级名字
     *
     * @param pageNo   the page no
     * @param pageSize the page size
     * @param keys     the keys
     * @param model    the model
     * @return the string
     */
    @GetMapping("/findEmployeeByKeysForSalary")
    public String findEmployeesByKeysForSalary(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                      @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                      @RequestParam("keys") String keys, Model model) {
        //如果给出的页面大小<=0，则将其设置为10
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PaginationSupport<EmployeeInfoForAdmin> employeeList = employeeService.findEmployeesByKeys(pageNo, pageSize, keys);
        System.out.println(employeeList.getItems().toString());
        model.addAttribute("employeeList", employeeList);
        return "paySalary";
    }
}